using System.Windows;
using System.Windows.Media;
using Microsoft.Win32;
using System.IO;

namespace LicenseApp.Client;

/// <summary>
/// 授权注册对话框
/// </summary>
public partial class LicenseRegistrationDialog : Window
{
    public bool IsRegistered { get; private set; }
    private bool _isPublicKeyValid = false;

    public LicenseRegistrationDialog(string message, Window? owner = null)
    {
        InitializeComponent();

        // 设置父窗口
        if (owner != null)
        {
            Owner = owner;
        }
        else
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
        }

        // 提示信息现在显示在授权状态区域，这里不再需要设置

        // 检查公钥状态
        CheckPublicKeyStatus();

        // 检查现有授权文件并显示信息
        CheckExistingLicense();

        // 初始化机器码显示
        InitializeMachineCode();
    }

    private void BtnPaste_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (Clipboard.ContainsText())
            {
                txtLicenseCode.Text = Clipboard.GetText();
            }
        }
        catch
        {
            // 忽略粘贴错误
        }
    }

    private void BtnClear_Click(object sender, RoutedEventArgs e)
    {
        // 清空输入框，让用户可以输入新的授权码
        txtLicenseCode.Clear();
        txtLicenseCode.Focus(); // 聚焦到输入框
    }

    private void CheckPublicKeyStatus()
    {
        try
        {
            // 应用程序路径获取 - 按要求实现
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            string publicKeyPath = System.IO.Path.Combine(assemblyDirPath, "public.xml");

            if (File.Exists(publicKeyPath))
            {
                var publicKeyContent = File.ReadAllText(publicKeyPath);

                // 验证公钥格式
                if (IsValidPublicKey(publicKeyContent))
                {
                    // 公钥有效，隐藏公钥检查区域
                    _isPublicKeyValid = true;
                    HidePublicKeySection();

                    // 启用授权码输入（始终允许输入新授权码）
                    EnableLicenseCodeInput();

                    // 调整对话框大小
                    AdjustDialogSize(false);
                }
                else
                {
                    // 公钥格式错误，显示公钥检查区域
                    _isPublicKeyValid = false;
                    ShowPublicKeySection();

                    txtPublicKeyStatus.Text = "❌ 格式错误";
                    txtPublicKeyStatus.Foreground = Brushes.Red;
                    txtPublicKeyInfo.Text = "公钥文件格式不正确，请重新导入";

                    // 禁用授权码输入
                    DisableLicenseCodeInput();

                    // 调整对话框大小
                    AdjustDialogSize(true);
                }
            }
            else
            {
                // 公钥不存在，显示公钥检查区域
                _isPublicKeyValid = false;
                ShowPublicKeySection();

                txtPublicKeyStatus.Text = "❌ 未导入";
                txtPublicKeyStatus.Foreground = Brushes.Red;
                txtPublicKeyInfo.Text = $"请导入公钥文件到: {publicKeyPath}";

                // 禁用授权码输入
                DisableLicenseCodeInput();

                // 调整对话框大小
                AdjustDialogSize(true);
            }
        }
        catch (Exception ex)
        {
            // 异常时显示公钥检查区域
            _isPublicKeyValid = false;
            ShowPublicKeySection();

            txtPublicKeyStatus.Text = "❌ 检查失败";
            txtPublicKeyStatus.Foreground = Brushes.Red;
            txtPublicKeyInfo.Text = $"检查公钥状态时发生错误: {ex.Message}";

            // 禁用授权码输入
            DisableLicenseCodeInput();

            // 调整对话框大小
            AdjustDialogSize(true);
        }
    }

    private void ShowPublicKeySection()
    {
        groupBoxPublicKey.Visibility = Visibility.Visible;
    }

    private void HidePublicKeySection()
    {
        groupBoxPublicKey.Visibility = Visibility.Collapsed;
    }

    private void EnableLicenseCodeInput()
    {
        txtLicenseCode.IsEnabled = true;
        btnRegister.IsEnabled = true;
        btnPaste.IsEnabled = true;
        btnClear.IsEnabled = true;
    }

    private void DisableLicenseCodeInput()
    {
        txtLicenseCode.IsEnabled = false;
        btnRegister.IsEnabled = false;
        btnPaste.IsEnabled = false;
        btnClear.IsEnabled = false;
    }

    private void AdjustDialogSize(bool showPublicKeySection)
    {
        if (showPublicKeySection)
        {
            // 显示公钥检查区域时的高度（增加了详细提示信息的空间）
            Height = 620;
        }
        else
        {
            // 隐藏公钥检查区域时的高度（增加了详细提示信息的空间）
            Height = 500;
        }
    }

    private void CheckExistingLicense()
    {
        try
        {
            // 应用程序路径获取 - 按要求实现
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            string licenseFilePath = System.IO.Path.Combine(assemblyDirPath, "System.ZhyLsHK.dll");

            if (File.Exists(licenseFilePath))
            {
                // 读取授权文件内容
                string licenseContent = File.ReadAllText(licenseFilePath);

                if (!string.IsNullOrWhiteSpace(licenseContent))
                {
                    // 预加载授权码到输入框
                    txtLicenseCode.Text = licenseContent;

                    // 尝试解析授权信息
                    var licenseInfo = LicenseManager.GetLicenseInfo();
                    var statusInfo = LicenseManager.GetCurrentStatus();

                    if (licenseInfo != null)
                    {
                        // 更新提示信息，显示当前授权详情
                        UpdateMessageWithLicenseInfo(licenseInfo, statusInfo);
                    }
                    else
                    {
                        // 🎯 授权文件存在但验证失败，显示具体的失败原因
                        UpdateMessageWithDetailedError(statusInfo);
                    }
                }
            }
            else
            {
                // 如果没有授权文件，显示未授权状态
                UpdateLicenseStatusDisplay(null, null);
            }
        }
        catch (Exception ex)
        {
            // 读取授权文件时发生错误，显示错误信息
            UpdateMessageWithError(ex.Message);
        }
    }

    private void UpdateMessageWithLicenseInfo(LicenseInfo licenseInfo, LicenseStatusInfo statusInfo)
    {
        // 使用新的统一显示方法
        UpdateLicenseStatusDisplay(licenseInfo, statusInfo);
    }

    private void UpdateMessageWithDetailedError(LicenseStatusInfo statusInfo)
    {
        // 根据具体的错误类型显示相应的状态和建议
        if (IsTimeRelatedError(statusInfo.Message))
        {
            txtLicenseStatus.Text = "时间验证失败";
            txtLicenseStatus.Foreground = Brushes.Orange;
            txtLicenseDetails.Text = $"{statusInfo.Message}\n\n请同步到正确的时间后重试。";
        }
        else if (statusInfo.Message.Contains("格式错误") || statusInfo.Message.Contains("签名验证失败"))
        {
            txtLicenseStatus.Text = "授权码验证失败";
            txtLicenseStatus.Foreground = Brushes.Red;
            txtLicenseDetails.Text = $"{statusInfo.Message}\n\n请确认授权码和公钥是配套的。";
        }
        else if (statusInfo.Message.Contains("已过期"))
        {
            txtLicenseStatus.Text = "授权已过期";
            txtLicenseStatus.Foreground = Brushes.Red;
            txtLicenseDetails.Text = $"{statusInfo.Message}\n\n请联系供应商获取新的授权码。";
        }
        else if (statusInfo.Message.Contains("未找到授权码文件"))
        {
            txtLicenseStatus.Text = "未找到授权文件";
            txtLicenseStatus.Foreground = Brushes.Gray;
            txtLicenseDetails.Text = $"{statusInfo.Message}\n\n请输入授权码进行注册。";
        }
        else
        {
            txtLicenseStatus.Text = "授权验证失败";
            txtLicenseStatus.Foreground = Brushes.Red;
            txtLicenseDetails.Text = $"{statusInfo.Message}\n\n请输入有效的授权码重新注册。";
        }

        txtLicenseDetails.Visibility = Visibility.Visible;
    }

    private void UpdateMessageWithInvalidLicense()
    {
        // 保留此方法以兼容其他调用（如果有的话）
        txtLicenseStatus.Text = "发现授权文件但无法解析";
        txtLicenseDetails.Text = "授权文件可能已损坏或格式不正确，请输入有效的授权码重新注册。";
        txtLicenseDetails.Visibility = Visibility.Visible;
    }

    private void UpdateMessageWithError(string errorMessage)
    {
        // 错误信息现在显示在授权状态区域
        txtLicenseStatus.Text = "检查授权文件时发生错误";
        txtLicenseDetails.Text = $"{errorMessage}\n\n请输入授权码进行注册。";
        txtLicenseDetails.Visibility = Visibility.Visible;
    }

    /// <summary>
    /// 判断是否为时间相关的错误
    /// </summary>
    private bool IsTimeRelatedError(string errorMessage)
    {
        return errorMessage.Contains("回拨时间") ||
               errorMessage.Contains("时间回拨") ||
               errorMessage.Contains("停滞") ||
               errorMessage.Contains("时间锁定") ||
               errorMessage.Contains("系统时间未超过");
    }

    private string GetStatusText(LicenseStatus status)
    {
        return status switch
        {
            LicenseStatus.Valid => "✅ 有效",
            LicenseStatus.ExpiringSoon => "⚠️ 即将到期",
            LicenseStatus.ExpiredGracePeriod => "🕐 过期(宽限期)",
            LicenseStatus.Expired => "❌ 已过期",
            _ => "❓ 未知"
        };
    }

    private string GetStatusIcon(LicenseStatus status)
    {
        return status switch
        {
            LicenseStatus.Valid => "✅",
            LicenseStatus.ExpiringSoon => "⚠️",
            LicenseStatus.ExpiredGracePeriod => "🕐",
            LicenseStatus.Expired => "❌",
            _ => "❓"
        };
    }

    /// <summary>
    /// 刷新授权状态显示
    /// </summary>
    private void RefreshLicenseStatus()
    {
        try
        {
            var licenseInfo = LicenseManager.GetLicenseInfo();
            var statusInfo = LicenseManager.GetCurrentStatus();
            UpdateLicenseStatusDisplay(licenseInfo, statusInfo);
        }
        catch (Exception ex)
        {
            UpdateMessageWithError(ex.Message);
        }
    }

    /// <summary>
    /// 更新授权状态显示区域
    /// </summary>
    private void UpdateLicenseStatusDisplay(LicenseInfo? licenseInfo, LicenseStatusInfo? statusInfo)
    {
        if (licenseInfo != null && statusInfo != null)
        {
            // 有有效授权
            switch (statusInfo.Status)
            {
                case LicenseStatus.Valid:
                    txtLicenseStatus.Text = "✅ 授权有效";
                    txtLicenseStatus.Foreground = Brushes.Green;
                    break;
                case LicenseStatus.ExpiringSoon:
                    txtLicenseStatus.Text = "⚠️ 授权即将到期";
                    txtLicenseStatus.Foreground = Brushes.Orange;
                    break;
                case LicenseStatus.Expired:
                    txtLicenseStatus.Text = "❌ 授权已过期";
                    txtLicenseStatus.Foreground = Brushes.Red;
                    break;
                default:
                    txtLicenseStatus.Text = "❓ 授权状态未知";
                    txtLicenseStatus.Foreground = Brushes.Gray;
                    break;
            }

            // 显示详细信息
            txtLicenseDetails.Text = $"AGV数量: {licenseInfo.AgvCount} 台\n" +
                                   $"生效日期: {licenseInfo.StartDate:yyyy-MM-dd}\n" +
                                   $"到期日期: {licenseInfo.EndDate:yyyy-MM-dd}\n" +
                                   $"剩余天数: {licenseInfo.RemainingDays} 天";
            txtLicenseDetails.Visibility = Visibility.Visible;
        }
        else
        {
            // 无有效授权
            txtLicenseStatus.Text = "● 未找到有效授权";
            txtLicenseStatus.Foreground = Brushes.Gray;
            txtLicenseDetails.Text = "请输入授权码进行注册";
            txtLicenseDetails.Visibility = Visibility.Visible;
        }
    }

    private bool IsValidPublicKey(string publicKeyContent)
    {
        try
        {
            return !string.IsNullOrWhiteSpace(publicKeyContent) &&
                   publicKeyContent.Contains("<RSAKeyValue>") &&
                   publicKeyContent.Contains("<Modulus>") &&
                   publicKeyContent.Contains("<Exponent>");
        }
        catch
        {
            return false;
        }
    }

    private void BtnImportPublicKey_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var openFileDialog = new OpenFileDialog
            {
                Title = "选择公钥文件",
                Filter = "XML文件 (*.xml)|*.xml|所有文件 (*.*)|*.*",
                DefaultExt = "xml"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                ImportPublicKeyFile(openFileDialog.FileName);
            }
        }
        catch (Exception ex)
        {
            LicenseHelper.ShowNonBlockingDialog(
                "导入失败",
                $"导入公钥文件时发生错误: {ex.Message}",
                LicenseDialogType.Error,
                this);
        }
    }

    private void ImportPublicKeyFile(string sourceFile)
    {
        try
        {
            // 读取并验证公钥内容
            string publicKeyContent = File.ReadAllText(sourceFile);

            if (!IsValidPublicKey(publicKeyContent))
            {
                LicenseHelper.ShowNonBlockingDialog(
                    "格式错误",
                    "选择的文件不是有效的公钥文件。\n\n有效的公钥文件应包含RSA密钥信息。",
                    LicenseDialogType.Error,
                    this);
                return;
            }

            // 应用程序路径获取 - 按要求实现
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            string targetPath = System.IO.Path.Combine(assemblyDirPath, "public.xml");

            // 复制文件
            File.Copy(sourceFile, targetPath, true);

            // 初始化授权系统
            bool initResult = LicenseManager.Initialize(publicKeyContent);

            if (initResult)
            {
                LicenseHelper.ShowNonBlockingDialog(
                    "导入成功",
                    "公钥文件导入成功！现在可以注册授权码了。",
                    LicenseDialogType.Information,
                    this);

                // 刷新公钥状态（会自动隐藏公钥检查区域并调整大小）
                CheckPublicKeyStatus();
            }
            else
            {
                LicenseHelper.ShowNonBlockingDialog(
                    "初始化失败",
                    "公钥导入成功，但初始化授权系统时出错。",
                    LicenseDialogType.Error,
                    this);
            }
        }
        catch (Exception ex)
        {
            LicenseHelper.ShowNonBlockingDialog(
                "导入失败",
                $"导入公钥文件时发生错误: {ex.Message}",
                LicenseDialogType.Error,
                this);
        }
    }

    private void BtnRegister_Click(object sender, RoutedEventArgs e)
    {
        // 先检查公钥状态（使用状态变量而不是UI文本）
        if (!_isPublicKeyValid)
        {
            LicenseHelper.ShowNonBlockingDialog(
                "无法注册",
                "请先导入有效的公钥文件，然后再注册授权码。",
                LicenseDialogType.Warning,
                this);
            return;
        }

        var licenseCode = txtLicenseCode.Text.Trim();

        if (string.IsNullOrEmpty(licenseCode))
        {
            LicenseHelper.ShowNonBlockingDialog(
                "输入错误",
                "请输入授权码",
                LicenseDialogType.Warning,
                this);
            return;
        }

        try
        {
            // 🎯 先检查注册风险
            var riskCheck = LicenseValidator.GetRegistrationRisk(licenseCode);

            if (!riskCheck.CanRegister)
            {
                // 不能注册（如重复注册相同有效授权）
                LicenseHelper.ShowNonBlockingDialog(
                    "无法注册",
                    riskCheck.Message,
                    LicenseDialogType.Warning,
                    this);
                return;
            }

            if (riskCheck.RequiresConfirmation)
            {
                // 需要用户确认风险（如替换当前有效授权）
                var confirmResult = MessageBox.Show(
                    riskCheck.Message + "\n\n是否确认继续注册？",
                    "风险确认",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning,
                    MessageBoxResult.No);

                if (confirmResult != MessageBoxResult.Yes)
                {
                    return; // 用户取消注册
                }

                // 用户确认后，使用带确认参数的注册方法
                bool success = LicenseValidator.RegisterLicense(licenseCode, true);
                HandleRegistrationResult(success, licenseCode);
            }
            else
            {
                // 安全注册，直接执行
                bool success = LicenseManager.RegisterLicense(licenseCode);
                HandleRegistrationResult(success, licenseCode);
            }
        }
        catch (Exception ex)
        {
            LicenseHelper.ShowNonBlockingDialog(
                "注册异常",
                $"注册过程中发生错误: {ex.Message}",
                LicenseDialogType.Error,
                this);
        }
    }

    /// <summary>
    /// 处理注册结果
    /// </summary>
    private void HandleRegistrationResult(bool success, string licenseCode)
    {
        if (success)
        {
            IsRegistered = true;

            // 获取授权信息
            var licenseInfo = LicenseManager.GetLicenseInfo();
            string successMessage = "授权码注册成功！";

            if (licenseInfo != null)
            {
                successMessage += $"\n\n授权信息：" +
                                $"\n授权设备：{licenseInfo.AgvCount} 台AGV" +
                                $"\n生效日期：{licenseInfo.StartDate:yyyy-MM-dd}" +
                                $"\n到期日期：{licenseInfo.EndDate:yyyy-MM-dd}" +
                                $"\n授权天数：{licenseInfo.Days} 天" +
                                $"\n剩余天数：{licenseInfo.RemainingDays} 天";
            }

            LicenseHelper.ShowNonBlockingDialog(
                "注册成功",
                successMessage,
                LicenseDialogType.Information,
                this);

            // 刷新授权状态显示，而不是关闭对话框
            RefreshLicenseStatus();
        }
        else
        {
            // 🎯 获取详细的失败原因
            string detailedReason = GetRegistrationFailureReason(licenseCode);

            LicenseHelper.ShowNonBlockingDialog(
                "注册失败",
                detailedReason,
                LicenseDialogType.Error,
                this);
        }
    }

    /// <summary>
    /// 获取注册失败的详细原因
    /// </summary>
    private string GetRegistrationFailureReason(string licenseCode)
    {
        try
        {
            // 1. 检查授权码格式和签名
            var licenseInfo = LicenseValidator.ValidateLicenseCode(licenseCode);
            if (licenseInfo == null)
            {
                return "授权码注册失败：\n\n" +
                       "授权码格式错误或签名验证失败\n\n" +
                       "可能的原因：\n" +
                       "• 授权码格式不正确\n" +
                       "• 公钥与授权码不匹配\n" +
                       "• 授权码已损坏\n\n" +
                       "请确认授权码和公钥是配套的。";
            }

            // 2. 检查时间和使用天数验证
            var validation = UnifiedLicenseGuard.ValidateLicense(licenseInfo);
            if (!validation.IsValid)
            {
                return $"授权码注册失败：\n\n" +
                       $"❌ {validation.Message}\n\n" +
                       "请确认授权码是从合法渠道获取的，且在有效期内。";
            }

            // 3. 如果验证都通过了，说明是保存失败
            return "授权码注册失败：\n\n" +
                   "❌ 授权码保存失败\n\n" +
                   "可能的原因：\n" +
                   "• 磁盘空间不足\n" +
                   "• 文件权限不足\n" +
                   "• 系统资源不足\n\n" +
                   "请检查系统状态后重试。";
        }
        catch (Exception ex)
        {
            return $"授权码注册失败：\n\n" +
                   $"❌ 注册过程中发生异常\n\n" +
                   $"错误详情：{ex.Message}\n\n" +
                   "请联系技术支持。";
        }
    }

    private void BtnCancel_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    private void BtnLater_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    #region 机器码相关功能

    /// <summary>
    /// 初始化机器码显示
    /// </summary>
    private void InitializeMachineCode()
    {
        try
        {
            RefreshMachineCode();
        }
        catch (Exception ex)
        {
            txtMachineCode.Text = "获取失败";
            txtMachineCode.ToolTip = $"获取机器码失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 刷新机器码显示
    /// </summary>
    private void RefreshMachineCode()
    {
        try
        {
            var machineCode = MachineCodeGenerator.GenerateMachineCode();
            txtMachineCode.Text = machineCode;
            txtMachineCode.ToolTip = $"机器码: {machineCode}\n生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n\n将此机器码发送给供应商以获取绑定授权码";
        }
        catch (Exception ex)
        {
            txtMachineCode.Text = "获取失败";
            txtMachineCode.ToolTip = $"获取机器码失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 复制机器码按钮点击事件
    /// </summary>
    private void BtnCopyMachineCode_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(txtMachineCode.Text) && txtMachineCode.Text != "获取失败")
            {
                Clipboard.SetText(txtMachineCode.Text);
                MessageBox.Show($"机器码已复制到剪贴板！\n\n机器码: {txtMachineCode.Text}\n\n请将此机器码发送给供应商，以获取绑定到当前机器的授权码。",
                              "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("没有可复制的机器码", "提示",
                              MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"复制机器码失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 刷新机器码按钮点击事件
    /// </summary>
    private void BtnRefreshMachineCode_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            RefreshMachineCode();
            MessageBox.Show("机器码已刷新", "提示",
                          MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"刷新机器码失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    /// <summary>
    /// 机器码详细信息按钮点击事件
    /// </summary>
    private void BtnMachineCodeDetails_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var details = MachineCodeGenerator.GetMachineCodeComponents();
            MessageBox.Show(details, "机器码详细信息",
                          MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"获取机器码详细信息失败: {ex.Message}", "错误",
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    #endregion
}
